package com.brotherly.mpgp.remoteinterface;

import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.security.Key;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.crypto.Cipher;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.simple.parser.JSONParser;

import com.brotherly.framework.http.HttpListener;
import com.brotherly.framework.http.HttpService;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.util.JSonSax;
import com.brotherly.util.URIBuilder;
import com.brotherly.util.URIBuilder.PathBuilder;

public class RemoteServer
{
    public static class RemoteServerHttpListener implements HttpListener
    {
        public byte[] body;
        public int code;
        public Map<String, String> headers;

        public String getContent()
        {
            if (body == null)
                return null;

            try
            {
                return new String(body, "utf-8");
            }
            catch (Exception e)
            {}

            return null;
        }

        @Override
        public void result(int code, Map<String, String> headers, byte[] body)
        {
            this.code = code;
            this.headers = headers;
            this.body = body;
        }
    }

    public static class SessionInfo
    {
        public int id;
        public long last_modified;
        public String nickname;
        public String session;
        public SessionStub stub;
        public String uri;
        public String username;
    }

    public static class SessionStub
    {
        public static SessionStub fromJson(String json)
        {
            SessionStub stub = null;

            try
            {
                JSONTokener jsonParser = new JSONTokener(json);
                JSONObject items = (JSONObject) jsonParser.nextValue();
                stub = new SessionStub();
                stub.username = items.getString("username");
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return stub;
        }

        public static String toJSon(SessionStub stub)
        {
            StringWriter writer = new StringWriter();

            JSonSax sax = new JSonSax(writer);

            sax.startMap();

            sax.writeString("username");
            sax.writeString(stub.username);

            sax.endMap();

            return writer.toString();
        }

        public String username;
    }

    protected static String decrypt(PublicKey key, byte[] cryptograph)
    {
        String content = null;

        try
        {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

            byte[] plaintext = doCipher(Cipher.DECRYPT_MODE, key, cryptograph, cipher, 256);

            content = new String(plaintext, "utf-8");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return content;
    }

    public static byte[] digest(byte[] plaintext)
    {
        byte[] data = null;

        try
        {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            digest.update(plaintext);

            data = digest.digest();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return data;
    }

    protected static byte[] doCipher(int opmode, Key key, byte[] plaintext, Cipher cipher, int blockSize) throws Exception
    {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        cipher.init(opmode, key);

        int count = plaintext.length / blockSize;
        count += (plaintext.length % blockSize != 0) ? 1 : 0;

        for (int index = 0; index != count; ++index)
        {
            int begin = index * blockSize;
            int end = index * blockSize + blockSize;

            if (end > plaintext.length)
                end = plaintext.length;

            byte[] data = new byte[end - begin];
            System.arraycopy(plaintext, begin, data, 0, data.length);

            byte[] output = cipher.doFinal(data);

            stream.write(output);

            cipher.init(opmode, key);
        }

        return stream.toByteArray();
    }

    protected static byte[] encrypt(PublicKey key, String content)
    {
        byte[] cryptograph = null;

        try
        {
            byte[] plaintext = content.getBytes("utf-8");

            cryptograph = plaintext;

            /*
             * Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
             * 
             * cryptograph = doCipher(Cipher.ENCRYPT_MODE, key, plaintext,
             * cipher, 245);
             */
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return cryptograph;
    }

    public int code;

    private HttpService httpService;

    public RemoteServer()
    {
        super();
        httpService = (HttpService) ServiceManager.getInstance().getService(ServiceManager.HTTP_SERVICE);
    }

    public int changeInformation(String sessionRoot, SessionInfo session, User user) throws JSONException
    {
        String json = User.toJSONString(user).toString();

        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("changeUserinfo").putParameter("session", session.session);

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "post", null, json.getBytes("utf-8"), listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return code;

        String content = listener.getContent();

        JSONObject body = null;
        try
        {
            body = (JSONObject) (new JSONParser()).parse(content);
        }
        catch (Exception e)
        {
            return code;
        }

        code = body.getInt("status");

        return code;
    }

    protected SessionInfo decryptSessionInfo(PublicKey key, byte[] data)
    {
        JSONObject body = null;

        try
        {
            String content = new String(data, "utf-8");
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 == 2)
            {
                JSONObject session_data = (JSONObject) body.get("data");

                SessionInfo sessionInfo = new SessionInfo();

                sessionInfo.id = session_data.getInt("id");
                sessionInfo.session = session_data.getString("session");
                sessionInfo.username = session_data.getString("username");
                sessionInfo.nickname = session_data.getString("nickname");
                sessionInfo.last_modified = session_data.getLong("last_modified");
                sessionInfo.uri = session_data.getString("uri");
                return sessionInfo;
            }
        }
        catch (Exception e)
        {
            return null;
        }

        return null;
    }

    public boolean existedThird(String sessionRoot, String third, String value)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("existedthirds").putParameter("third", third).putParameter("value", value);

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return false;

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            return body.getBoolean("existed");
        }
        catch (Exception e)
        {
            return false;
        }

    }

    public SessionInfo login(String sessionRoot, String openid, String accesstoken, String expiresin)
    {
        JSONObject items = new JSONObject();

        URIBuilder builder = new URIBuilder(sessionRoot);
        builder.getPath().pushPath("login_t");
        SessionStub stub = new SessionStub();
        byte[] data = null;

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            items.put("username", stub.username);
            String json = items.toString();
            data = encrypt(null, json);
            httpService.request(builder.toString(), "post", null, data, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return null;

        SessionInfo sessionInfo = decryptSessionInfo(null, listener.body);
        if (sessionInfo == null)
            return null;

        sessionInfo.stub = stub;

        return sessionInfo;
    }

    public void logout(String sessionRoot, SessionInfo session)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("logout").putParameter("session", session.session);

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, false);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public JSONObject queryHotwords(String sessionRoot, SessionInfo session, int type)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("queryhotkeysstat").putParameter("session", session.session)
                .putParameter("type", String.valueOf(type));

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 != 2)
                return null;

            return (JSONObject) body.get("keywords");
        }
        catch (Exception e)
        {
            return null;
        }

    }

    public JSONArray queryKeywords(String sessionRoot, SessionInfo session, int type)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("queryhotkeys").putParameter("session", session.session)
                .putParameter("type", String.valueOf(type));

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 != 2)
                return null;

            return (JSONArray) body.get("keywords");
        }
        catch (Exception e)
        {
            return null;
        }

    }

    public String queryScore(String sessionRoot, SessionInfo session, long scope)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("queryscore").putParameter("session", session.session)
                .putParameter("scope", String.valueOf(scope));

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return "";

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 != 2)
                return null;
            return body.get("scores").toString();

        }
        catch (Exception e)
        {
            return "";
        }

    }

    public JSONObject queryUser(String sessionRoot, int id)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("getuser").putParameter("id", String.valueOf(id));

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 != 2)
                return null;
            return (JSONObject) body.get("data");
        }
        catch (Exception e)
        {
            return null;
        }

    }

    public JSONObject requestCustomChannel(String aroundRoot, SessionInfo session, String json)
    {
        URIBuilder builder = new URIBuilder(aroundRoot);

        builder.getPath().pushPath("manager").pushPath("customChannel").putParameter("session", session.session);

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Content-Type", "text/plain;charset=UTF-8");

        try
        {
            httpService.request(builder.toString(), "post", headers, json.getBytes("utf-8"), listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 != 2)
                return null;
            return body;
        }
        catch (Exception e)
        {
            return null;
        }

    }

    public JSONObject requestGuideInfo(String guideRoot)
    {
        URIBuilder builder = new URIBuilder(guideRoot);

        builder.getPath().pushPath("getprofile").putParameter("name", "entry");

        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        try
        {
            httpService.request(builder.toString(), "get", null, null, listener, true);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();

        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            code = body.getInt("status");
            if (code / 100 != 2)
                return null;
            return body;
        }
        catch (Exception e)
        {
            return null;
        }

    }

    public JSONArray gameIdentifier(String remoteServerRoot, Set<String> gamePackageName)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);

        builder.getPath().pushPath("games/identifier");
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        JSONObject jsonObject = new JSONObject();
        JSONArray identifiers = new JSONArray();
        for (String game : gamePackageName)
        {
            identifiers.put(game);
        }
        try
        {
            jsonObject.put("identifiers", identifiers);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        httpService.request(builder.toString(), "post", null, jsonObject.toString().getBytes(), listener, true);
        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("status") && body.getInt("status") == 200)
            {
                JSONArray jsonarray = body.getJSONArray("body");

                return jsonarray;
            } else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public JSONObject gameArticles(String remoteServerRoot, List<String> gamePackageName, int index, int count)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);

        builder.getPath().pushPath("articles/get");
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        JSONObject jsonObject = new JSONObject();
        JSONArray types = new JSONArray();
        types.put("promotion");
        types.put("course");
        JSONArray identifiers = new JSONArray();
        if (gamePackageName != null)
        {
            for (String game : gamePackageName)
            {
                identifiers.put(game);
            }
        }
        try
        {
            jsonObject.put("types", types);
            if (gamePackageName != null)
            {
                jsonObject.put("identifiers", identifiers);
            }
            jsonObject.put("index", index);
            jsonObject.put("count", count);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        httpService.request(builder.toString(), "post", null, jsonObject.toString().getBytes(), listener, true);
        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("status") && body.getInt("status") == 200)
            {
                // JSONArray jsonarray = body.getJSONArray("body");
                return body;
            } else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public JSONObject gameRecommend(String remoteServerRoot, List<String> gamePackageName, String tag, int index, int count)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);

        PathBuilder pb = builder.getPath().pushPath("games/find");
        if (tag != null)
        {
            pb.putParameter("tag", tag);
        }
        pb.putParameter("index", index + "").putParameter("count", count + "");
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        JSONObject jsonObject = new JSONObject();
        JSONArray identifiers = new JSONArray();
        for (String game : gamePackageName)
        {
            identifiers.put(game);
        }
        if (identifiers.length() == 0)
        {
            identifiers.put("");
        }
        try
        {
            jsonObject.put("identifiers", identifiers);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        httpService.request(builder.toString(), "post", null, jsonObject.toString().getBytes(), listener, true);
        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("status") && body.getInt("status") == 200)
            {
                return body;
            } else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public JSONArray gameTags(String remoteServerRoot)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);

        builder.getPath().pushPath("games/tags");
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "get", null, null, listener, true);
        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("status") && body.getInt("status") == 200)
            {
                JSONArray jsonarray = body.getJSONArray("body");

                return jsonarray;
            } else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public JSONArray gameRankNames(String remoteServerRoot)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);

        builder.getPath().pushPath("games/ranknames");
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "get", null, null, listener, true);
        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("status") && body.getInt("status") == 200)
            {
                JSONArray jsonarray = body.getJSONArray("body");

                return jsonarray;
            } else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public boolean userExisted(String sessionRoot, String platform, String openid, String accesstoken)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("reg.do").putParameter("newUser", "").putParameter("pf", platform)
                .putParameter("token", accesstoken)
                .putParameter("pfId", openid);
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "get", null, null, listener, true);
        code = listener.code;
        if (listener.body == null)
            return false;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("f") && body.getInt("f") == 1 && body.has("m") && body.getString("m").equals("n"))
            {
                return true;
            } else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

    }

    public String userID(String sessionRoot, String platform, String openid, String accesstoken)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("reg.do").putParameter("getUserId", "").putParameter("pf", platform)
                .putParameter("pfId", openid).putParameter("token", accesstoken);
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "get", null, null, listener, true);
        code = listener.code;
        if (listener.body == null)
            return null;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("f") && body.getInt("f") == 1 && body.has("m"))
            {
                return body.getString("m");
            } else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            return null;
        }

    }

    public int userRegister(String sessionRoot, String avatar, String sex, String nickname, String birthday, String lon,
            String lat, String platform, String openid, String accesstoken)
    {

        URIBuilder builder = new URIBuilder(sessionRoot);
        builder.getPath().pushPath("reg.do").putParameter("avatar", avatar).putParameter("sex", sex)
                .putParameter("nick", nickname).putParameter("bir", birthday).putParameter("lon", lon).putParameter("lat", lat)
                .putParameter("token", accesstoken).putParameter("pf", platform).putParameter("pfId", openid);
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "get", null, null, listener, true);
        code = listener.code;
        if (listener.body == null)
            return -1;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("f") && body.getInt("f") == 1 && body.has("m"))
            {
                return Integer.parseInt(body.getString("m"));
            } else
            {
                return -1;
            }
        }
        catch (Exception e)
        {
            return -1;
        }
    }

    public int userRegisterStep(String sessionRoot, String id, String accesstoken)
    {
        URIBuilder builder = new URIBuilder(sessionRoot);

        builder.getPath().pushPath("reg.do").putParameter("regStep", "").putParameter("id", id)
                .putParameter("token", accesstoken);
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "get", null, null, listener, true);
        code = listener.code;
        if (listener.body == null)
            return 0;

        JSONObject body = null;

        String content = listener.getContent();
        try
        {
            JSONTokener jsonParser = new JSONTokener(content);
            body = (JSONObject) jsonParser.nextValue();
            if (body.has("f") && body.getInt("f") == 1 && body.has("m"))
            {
                return Integer.parseInt(body.getString("m"));
            } else
            {
                return 0;
            }
        }
        catch (Exception e)
        {
            return 0;
        }
    }

    public int publishSuggestionToServer(String remoteServerRoot, String content)
    {
        try
        {
            URIBuilder builder = new URIBuilder(remoteServerRoot);
            builder.getPath().pushPath("opinion/commit");
            JSONObject jsonContent = new JSONObject();
            jsonContent.put("content", content);
            String sendContent = jsonContent.toString();
            RemoteServerHttpListener listener = new RemoteServerHttpListener();
            httpService.request(builder.toString(), "post", null, sendContent.getBytes("utf-8"), listener, true);
            int code = listener.code;
            if (code == 200)
            {
                String jsonStr = listener.getContent();
                int result = new JSONObject(jsonStr).getInt("status");
                return result;
            }
            return 0;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return -1;
    }

    public JSONObject gameRank(String remoteServerRoot, String rankName, List<String> identifiersStr)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);
        builder.getPath().pushPath("games/ranks");
        builder.getPath().putParameter("name", rankName);
        JSONObject gameJson = new JSONObject();
        JSONArray identifiers = new JSONArray();
        for (String game : identifiersStr)
        {
            identifiers.put(game);
        }
        if (identifiers.length() == 0)
        {
            identifiers.put("");
        }
        try
        {
            gameJson.put("identifiers", identifiers);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        httpService.request(builder.toString(), "post", null, gameJson.toString().getBytes(), listener, true);
        int code = listener.code;
        if (code == 200)
        {
            try
            {
                String content = listener.getContent();
                JSONObject jsonObject = new JSONObject(content);
                int codeResponse = jsonObject.getInt("status");
                if (codeResponse == 200)
                {
                    return jsonObject;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }
        return null;
    }

    public JSONObject randRecommendGames(String remoteServerRoot, ArrayList<String> identifiersStr, int count)
    {
        URIBuilder builder = new URIBuilder(remoteServerRoot);
        builder.getPath().pushPath("games/recommend");
        builder.getPath().putParameter("count", Integer.toString(count));
        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        JSONObject jsonObject = new JSONObject();
        JSONArray identifiers = new JSONArray();
        for (String game : identifiersStr)
        {
            identifiers.put(game);
        }
        try
        {
            jsonObject.put("identifiers", identifiers);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        httpService.request(builder.toString(), "post", null, jsonObject.toString().getBytes(), listener, true);
        int code = listener.code;
        if (code == 200)
        {
            try
            {
                JSONObject jsonObjectResult = new JSONObject(listener.getContent());
                int codeResponse = jsonObjectResult.getInt("status");
                if (codeResponse == 200)
                {
                    return jsonObjectResult;
                }
            }
            catch (Exception e)
            {

            }

        }
        return null;

    }

    public JSONObject initDownLoad(String remoteServerRoot, ArrayList<String> types, ArrayList<String> identifiers,
            String rankName, int index, int count)
    {
        // TODO Auto-generated method stub

        URIBuilder builder = new URIBuilder(remoteServerRoot);
        builder.getPath().pushPath("super/init");
        builder.getPath().putParameter("ranks", rankName);

        RemoteServerHttpListener listener = new RemoteServerHttpListener();
        JSONObject postContent = new JSONObject();
        JSONArray typesJson = new JSONArray();
        for (String type : types)
        {
            typesJson.put(type);
        }

        JSONArray identifiersJson = new JSONArray();
        for (String identifier : identifiers)
        {
            identifiersJson.put(identifier);
        }

        try
        {
            postContent.put("types", typesJson);
            postContent.put("identifiers", identifiersJson);
            postContent.put("index", index);
            postContent.put("count", count);

            httpService.request(builder.toString(), "post", null, postContent.toString().getBytes(), listener, true);
            String returnResult = null;
            if (listener.code == 200)
            {
                returnResult = listener.getContent();
            }

            JSONObject result = new JSONObject(returnResult);
            return result;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    public JSONObject gameDetail(String remoteServerRoot, int gameref)
    {
        // TODO Auto-generated method stub
        URIBuilder builder = new URIBuilder(remoteServerRoot);
        builder.getPath().pushPath("games/get");
        builder.getPath().putParameter("gameref", gameref + "");
        RemoteServerHttpListener listener = new RemoteServerHttpListener();

        httpService.request(builder.toString(), "get", null, null, listener, true);

        if (listener.code == 200)
        {
            try
            {
                JSONObject result = new JSONObject(listener.getContent());
                return result;
            }
            catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        return null;
    }

}
